#!/usr/bin/env python

from slope import Slope
from backup import add_subelement

from xml.etree.ElementTree import SubElement

class Climber(object):
	"""Object which represents a climber"""
	def __init__(self, name, fullname, id, age=None, sexe=None, category=None):
		super(Climber, self).__init__()
		self.name = name
		self.fullname = fullname
		self.age = age
		self.sexe = sexe
		self.category = category
		self.id = id
		self._climbed_slopes = {}
		self.finalist = False
		
		self._final_climbed_slopes = {}
		
	def get_climbed_slopes(self):
		if self.finalist:
			return self._final_climbed_slopes
		else:
			return self._climbed_slopes
	climbed_slopes = property(fget=get_climbed_slopes)
	
	def get_score(self):
		result = [0, 0]
		for slope_id in self._climbed_slopes:
			slope = self._climbed_slopes[slope_id]
			result[0] += slope.get_value()
		for slope_id in self._final_climbed_slopes:
			slope = self._final_climbed_slopes[slope_id]
			result[1] += slope.get_value()
		return result
	
	def add_climbed_slope(self, slope):
		assert(isinstance(slope, Slope))
		if not slope.id in self.climbed_slopes:
			self.climbed_slopes[slope.id] = slope
			return True
		else:
			return False
		
	def remove_climbed_slope(self, slope_id):
#		assert(isinstance(slope, Slope))
		if slope_id in self.climbed_slopes.keys():
			del self.climbed_slopes[slope_id]
			return True
		else:
			return False
		
	def set_category(self, category):
		self.category = category
		
	def set_sexe(self, sexe):
		self.sexe = sexe
		
	def _add_node(self, xml_node):
		climber_node = add_subelement(xml_node, 'climber', None, id=str(self.id))
		name_node = add_subelement(climber_node, 'name', self.name)
		fullname_node = add_subelement(climber_node, 'fullname', self.fullname)
		age_node = add_subelement(climber_node, 'age', self.age)
		sexe_node = add_subelement(climber_node, 'sexe', self.sexe)
		category_node = add_subelement(climber_node, 'category', self.category)
		finalist_node = add_subelement(climber_node, 'finalist', int(self.finalist))
		slopes_node = add_subelement(climber_node, 'climbedslopes', None)
		for slope_id in self.climbed_slopes.keys():
			slope = self.climbed_slopes[slope_id]
			slope_node = add_subelement(slopes_node, 'slope', None, id=str(slope.id))

	def save(self, xml_node):
		self._add_node(xml_node)
